
/**
 * <video id="webcam"></video>
 * @param stream 
 */
function onSuccess(stream) {
	var video = document.getElementById('webcam') as HTMLVideoElement;
	if (window.URL) {
		video.src = window.URL.createObjectURL(stream);
	} else {
		video.src = stream;
	}
	video.autoplay = true;
	//or video.play();
}



export async function getUserMedia(constraints?: MediaStreamConstraints, onSuccess?, onError?) {
  const mediaDevices = navigator.mediaDevices;
  // @ts-ignore
  // prettier-ignore
  const UserMedia = mediaDevices.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia || navigator.msGetUserMedia;
  if (typeof UserMedia === 'function') {
    await UserMedia(constraints)
      .then(function (stream) {
        /* 使用这个 stream stream */
        onSuccess?.(stream);
      })
      .catch(function (err) {
        /* 处理 error */
        if (err.code === 'PERMISSION_DENIED') {
          console.error('用户拒绝提供信息');
        } else if (err.code === 'NOT_SUPPORTED_ERROR') {
          console.error('浏览器不支持指定的媒体类型');
        } else if (err.code === 'MANDATORY_UNSATISHIED_ERROR') {
          console.error('指定的媒体类型未收到媒体流');
        }

        onError?.(err);
      });

    return true;
  } else {
    console.error('your browser not support getUserMedia');
    return false;
  }
}
